package de.tg.handball.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

import de.tg.handball.data.Halle;
import de.tg.handball.data.Pair;
import de.tg.handball.data.Liga;
import de.tg.handball.data.Spiel;
import de.tg.handball.data.WebSource;

public class SisHandballConnector {

	public static String table_path = "//table/tbody";
	private static SimpleDateFormat formater = new SimpleDateFormat(
			"dd.MM.yy hh:mm");

	private WebSource url = null;

	TagNode spieleVorbei = null;
	TagNode spieleOffen = null;

	public SisHandballConnector(WebSource url) throws Exception {
		this.url = url;
	}

	@SuppressWarnings("unchecked")
	public void getData(InputStream input) throws Exception {
		try {
			HtmlCleaner clean = new HtmlCleaner();
			CleanerProperties props = clean.getProperties();
			props.setRecognizeUnicodeChars(true);
			TagNode node = clean.clean(new InputStreamReader(input));

			Object[] tableNode = node.evaluateXPath(table_path);

			for (Object object : tableNode) {
				TagNode tag = (TagNode) object;
				List<TagNode> child = (List<TagNode>) tag.getChildren();
				if (child.size() > 0) {
					TagNode tag2 = child.get(0);
					if (tag2.getChildren().size() == 10)
						spieleVorbei = tag;
					if (tag2.getChildren().size() == 7)
						spieleOffen = tag;

				}

			}
		} finally {
			input.close();
		}
	}

	public String checkSeite(FileOutputStream out) throws Exception {
		HttpURLConnection conn = null;
		BufferedWriter outWriter = null;
		BufferedReader read = null;
		try {
			MessageDigest digi = MessageDigest.getInstance("MD5");
			conn = (HttpURLConnection) new URL(url.getUrl()).openConnection();
			conn.setConnectTimeout(5000);
			read = new BufferedReader(
					new InputStreamReader(new DigestInputStream(
							conn.getInputStream(), digi), "UTF-8"));
			outWriter = new BufferedWriter(new OutputStreamWriter(out));
			String line = "";
			while ((line = read.readLine()) != null) {
				outWriter.write(line);
				outWriter.newLine();
			}

			outWriter.flush();
			return new String(digi.digest());

		} finally {
			if (read != null)
				read.close();
			if (conn != null)
				conn.disconnect();
			if (outWriter != null)
				outWriter.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Spiel> getErgebnisse(Liga rund) {
		List<Spiel> ret = new ArrayList<Spiel>();
		if (spieleVorbei == null)
			return ret;

		List<TagNode> childs = spieleVorbei.getChildren();

		int pos = 0;
		for (TagNode tag : childs) {
			if (pos == 0) {
				pos++;
				continue;
			}

			List<TagNode> spalte = tag.getChildren();

			if (spalte.size() != 10) {
				continue;
			}
			String datum1 = spalte.get(1).getText().toString();
			String datum2 = spalte.get(2).getText().toString();
			String heimStr = spalte.get(3).getText().toString();
			String gastStr = spalte.get(5).getText().toString();
			String tore = spalte.get(6).getText().toString();

			String heim = heimStr.trim();
			String gast = gastStr.trim();

			if (heim == null || gast == null)
				return null;

			Spiel spiel = null;
			try {
				Date datum = formater
						.parse(datum1.trim() + " " + datum2.trim());
				spiel = new Spiel(datum, rund.getName(), heim, gast);
				String[] split = tore.split(":");
				spiel.setErgebniss(new Pair<Integer, Integer>(Integer
						.parseInt(split[0]), Integer.parseInt(split[1])));
			} catch (ParseException e) {
				e.printStackTrace();
				continue;
			}

			if (spiel != null) {
				ret.add(spiel);
			}
		}

		return ret;
	}

	@SuppressWarnings("unchecked")
	public List<Spiel> getSpieleOffen(Liga rund) {
		List<Spiel> ret = new ArrayList<Spiel>();
		if (spieleOffen == null)
			return ret;
		List<TagNode> childs = spieleOffen.getChildren();

		int pos = 0;
		Spiel spiel = null;
		for (TagNode tag : childs) {
			if (pos == 0) {
				pos++;
				continue;
			}

			pos++;
			List<TagNode> spalte = tag.getChildren();

			if (spalte.size() == 3) {
				String halle = spalte.get(2).getText().toString();
				if (halle != null && halle.trim().length() > 0 && spiel != null) {
					spiel.setHalle(createHalle(halle));
				}
				continue;
			}

			if (spalte.size() != 7) {
				continue;
			}
			String datum1 = spalte.get(2).getText().toString();
			String datum2 = spalte.get(3).getText().toString();
			String heimStr = spalte.get(4).getText().toString();
			String gastStr = spalte.get(5).getText().toString();

			String heim = heimStr.trim();
			String gast = gastStr.trim();

			if (heim == null || gast == null)
				return null;
			try {
				Date datum = formater
						.parse(datum1.trim() + " " + datum2.trim());
				spiel = new Spiel(datum, rund.getName(), heim, gast);
			} catch (ParseException e) {
				e.printStackTrace();
			}

			if (spiel != null) {
				ret.add(spiel);
			}
		}
		return ret;
	}

	private Halle createHalle(String halleStr) {
		String[] split = halleStr.split(",");
		if (split.length != 3)
			return null;
		String name = split[0].trim();
		String strasse = split[1].trim();
		String ort = split[2].trim();
		Halle halle = new Halle(name, strasse, ort);
		return halle;
	}
}
